package handlers

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/gin-gonic/gin"

	"ai-doctor/services"
)

// 请求体结构
type ConsultRequest struct {
	Query string `json:"query" binding:"required"`
}

// 响应体结构
type ConsultResponse struct {
	Response string `json:"response"`
}

// 流式响应结构
type StreamResponse struct {
	Content string `json:"content"`
	Done    bool   `json:"done"`
}

// HandleConsultation 处理用户的中医咨询请求
func HandleConsultation(c *gin.Context) {
	var request ConsultRequest

	// 绑定JSON数据
	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求格式"})
		return
	}

	// 验证查询不能为空
	if request.Query == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "查询内容不能为空"})
		return
	}

	log.Printf("接收到咨询: %s", request.Query)

	// 调用腾讯混元大模型服务
	aiResponse, err := services.GetAIResponse(request.Query)
	if err != nil {
		log.Printf("AI响应错误: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取AI响应失败"})
		return
	}

	// 处理AI回复并格式化为中医风格
	formattedResponse := services.FormatTCMResponse(aiResponse)

	c.JSON(http.StatusOK, ConsultResponse{
		Response: formattedResponse,
	})
}

// HandleStreamConsultation 处理流式咨询请求
func HandleStreamConsultation(c *gin.Context) {
	var request ConsultRequest

	// 绑定JSON数据
	if err := c.ShouldBindJSON(&request); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求格式"})
		return
	}

	// 验证查询不能为空
	if request.Query == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "查询内容不能为空"})
		return
	}

	log.Printf("接收到流式咨询: %s", request.Query)

	// 设置响应头，支持Server-Sent Events
	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")
	c.Writer.Header().Set("Transfer-Encoding", "chunked")

	// 创建一个channel用于流式传输响应
	streamChan := make(chan string)

	// 在goroutine中调用流式API
	go func() {
		defer close(streamChan)
		fullContent, err := services.GetStreamingAIResponse(request.Query, streamChan)
		if err != nil {
			log.Printf("流式AI响应错误: %v", err)
			// 发送错误消息
			resp := StreamResponse{
				Content: fmt.Sprintf("获取AI响应失败: %v", err),
				Done:    true,
			}
			data, _ := json.Marshal(resp)
			c.SSEvent("message", string(data))
			return
		}

		log.Printf("流式响应完成，完整内容:\n%s\n", fullContent)
	}()

	// 刷新写入器以确保数据被发送
	flusher := c.Writer.(http.Flusher)

	// 处理来自channel的流式响应
	for chunk := range streamChan {
		// 格式化当前块
		resp := StreamResponse{
			Content: chunk,
			Done:    false,
		}

		data, err := json.Marshal(resp)
		if err != nil {
			log.Printf("JSON序列化错误: %v", err)
			continue
		}

		// 发送SSE格式的消息
		c.SSEvent("message", string(data))
		flusher.Flush()

		// // 添加小延迟，让前端有时间处理
		// time.Sleep(10 * time.Millisecond)
	}

	// 发送完成信号
	resp := StreamResponse{
		Content: "",
		Done:    true,
	}
	data, _ := json.Marshal(resp)
	c.SSEvent("message", string(data))
	flusher.Flush()
}
